﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Gio_Hang : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtCart = Session["Cart"] as DataTable;

            if (dtCart.Rows.Count == 0)
            {
                BlankCart();
            }
            else
            {
                LoadData();
            }
        }
    }

    void BlankCart()
    {
        DataTable dtCart = Session["Cart"] as DataTable;
        if (dtCart.Rows.Count == 0)
            lblThongBao.Text = "Giỏ hàng bạn đang trống. Mời bạn quay lại <a href='Default.aspx'>trang mua hàng</a>";
    }

    void LoadData()
    {
        DataTable dtCart = Session["Cart"] as DataTable;
        gv_InformationCart.DataSource = dtCart;    
        gv_InformationCart.DataBind();

        if (dtCart.Rows.Count == 0)
            return;
        else
        {
            gv_InformationCart.FooterRow.Cells[3].Text = "Tổng tiền";
            gv_InformationCart.FooterRow.Cells[4].Text = double.Parse(dtCart.Compute("Sum(TotalAmount)", "").ToString()).ToString("#,###,###") + " VNĐ";
        }
        
    }

    protected void gv_InformationCart_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gv_InformationCart.EditIndex = -1;
        LoadData();
    }
    protected void gv_InformationCart_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gv_InformationCart.EditIndex = e.NewEditIndex;
        LoadData();
    }
    protected void gv_InformationCart_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DataTable dtCart = Session["Cart"] as DataTable;
        DataRow r = dtCart.Rows[e.RowIndex];
        TextBox txt = (TextBox)gv_InformationCart.Rows
            [e.RowIndex].Cells[3].FindControl("txtQuantity");
        r["Quantity"] = int.Parse(txt.Text);
        gv_InformationCart.EditIndex = -1;
        LoadData();
    }
    protected void gv_InformationCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        DataTable dtCart = Session["Cart"] as DataTable;
        dtCart.Rows.RemoveAt(e.RowIndex);
        LoadData();
        BlankCart();
    }
    protected void btnPayment_Click(object sender, EventArgs e)
    {
        if (Session["Username"] == null)
        {
            lbThongBao.Text = "Bạn phải đăng nhập mới có thể thanh toán";
        }
        else
        {
            Response.Redirect("~/Thanh-toan.aspx");
        }
    }
    protected void btnComeBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }
}